#include "getService.h"
#include <nlohmann/json.hpp>

using JSON = nlohmann::json;

GetService::GetService()
:_success(false)
{}

static void JSONParse(string & ip,unsigned short & port,string & content){
    JSON js = JSON::parse(std::move(content));       
    int i = 0;
    bool found = false;
    for (JSON::iterator x = js.begin(); x != js.end(); ++x ) {
        for(JSON::iterator y = (*x).begin() ; y != (*x).end() ; ++y ){
            if(y.key()=="Service"){
                for(JSON::iterator z = y.value().begin() ; z != y.value().end() ; ++z ){
                    if(z.key() == "Address"){
                        ip = z.value();
                        ++i;
                        if(i==2){
                            found = true;
                            break;
                        }
                    }
                    if(z.key() == "Port"){
                        port = z.value();
                        ++i;
                        if(i==2){
                            found = true;
                            break;
                        }
                    }
                }
            }
            if(found == true){
                break;
            }
        }
        if(found == true){
            break;
        }
    }
}


void GetService::getService(string & ip,unsigned short & port,string serviceName)
{
    int i = 1;
    string httpReq = "http://192.168.220.128:8500/v1/health/service/"+serviceName+"?passing=true";
    std::cout<<httpReq<<"\n";

    WFHttpTask * httpTask=  WFTaskFactory::create_http_task( httpReq,10,10,[this,&ip,&port](WFHttpTask * task){
                protocol::HttpResponse *resp = task->get_resp();
                const void * body;
                size_t body_len = 0;
                resp->get_parsed_body(&body,&body_len);
                string content = (const char *)body;
                if(content == "[]"){
                    _success = false;
                    ip = "";
                    port = 0;
                }else{
                    JSONParse(ip,port,content);
                    _success = true;
                }
           }); 

    SeriesWork * series = Workflow::create_series_work(httpTask,[this,&i](const SeriesWork *){
        {    
            unique_lock<mutex> uqe(m_loak);
            --i;
            ilessOne.notify_all();
        }
    });

    series->start();

    unique_lock<mutex> uqe(m_loak);
    while(i > 0){
        ilessOne.wait(uqe);
    }
    
}


